/* eslint-env node */
const path = require('path')

const webpack           = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const fs                = require('fs-extra')
const jsonfile          = require('jsonfile')
const config            = require('config')


const argv = require('minimist')(process.argv.slice(2), {
	boolean: [
		'w',
	],
	alias: {
		w: 'watch',
	},
})

fs.writeFileSync(path.resolve(__dirname, 'config.json'), JSON.stringify(config))


const compiler = webpack({
	devtool: 'source-map',
	entry  : 'main.js',
	output : {
		path    : path.resolve('./dist/'),
		filename: '[name].js',
	},
	module: {
		loaders: [
			{
				test   : /\.pug$/,
				loaders: [
					'html-loader',
					`pug-html-loader?basedir=${path.resolve('./src')}`,
				],
			},
			{
				test   : /\.less$/,
				loaders: ['style-loader', 'css-loader', 'less-loader'],
			},
			{
				test   : /\.vue$/,
				loaders: ['vue-loader'],
			},
			{
				test   : /\.js$/,
				loaders: ['babel-loader'],
			},
			{
				test   : /\.json$/,
				loaders: ['json-loader'],
			},
		],
	},
	plugins: [
		new HtmlWebpackPlugin({
			template: 'src/pugs/index.pug',
		}),
		new webpack.DllReferencePlugin({
			context : __dirname,
			manifest: require('./dist/manifest.json'),
		}),
	],
	resolve: {
		root: [
			path.resolve('./src'),
		],
		extensions: [
			'',
			'.webpack.js',
			'.web.js',
			'.js',
			'.json',
			'.vue',
		],
		alias: {
			'config': path.resolve(__dirname, 'config.json'),

			'lodash'    : config.get('webpack.resolve.alias.lodash'),
			'vuex'      : config.get('webpack.resolve.alias.vuex'),
			'vue-router': config.get('webpack.resolve.alias.vue-router'),
			'axios'     : config.get('webpack.resolve.alias.axios'),
			'vue'       : config.get('webpack.resolve.alias.vue'),
			'store'     : config.get('webpack.resolve.alias.store'),
		},
	},
	vue: {
		loaders: {
			js: [
				'babel-loader',
			],
			pug: [
				'html-loader',
				{
					loader : 'pug-html-loader',
					options: {
						basedir: path.resolve('./src'),
					},
				},
			],
		},
		template: {
			basedir: path.resolve('./src'),
		},
	},
})


const cb = (err, stats) => {
	console.log(stats.toString('normal'))


	const file = './dist/stats/main.json'


	fs.ensureFileSync(file)

	jsonfile.writeFileSync(file, stats.toJson())
}

if (argv.watch) {
	compiler.watch({
		aggregateTimeout: 300,
	}, cb)
} else {
	compiler.run(cb)
}